<template>
  <div class="user-analysis">
    <!-- 行为趋势图 -->
    <el-card class="trend-card">
      <template #header>
        <div class="card-header">
          <span>行为趋势</span>
          <div class="header-right">
            <el-select v-model="currentBehaviorType" style="margin-right: 16px">
              <el-option
                v-for="type in behaviorTypes"
                :key="type.value"
                :label="type.label"
                :value="type.value"
              />
            </el-select>
            <el-select v-model="trendDays" @change="fetchBehaviorTrend">
              <el-option label="最近7天" :value="7" />
              <el-option label="最近30天" :value="30" />
              <el-option label="最近90天" :value="90" />
            </el-select>
          </div>
        </div>
      </template>
      <div class="chart-container">
        <v-chart :option="trendChartOption" autoresize />
      </div>
    </el-card>

    <!-- 分类偏好 -->
    <el-card class="preferences-card">
      <template #header>
        <div class="card-header">
          <span>分类偏好</span>
          <el-radio-group v-model="preferenceViewType" size="small">
            <el-radio-button label="list">列表</el-radio-button>
            <el-radio-button label="pie">饼图</el-radio-button>
          </el-radio-group>
        </div>
      </template>

      <!-- 列表视图 -->
      <div v-if="preferenceViewType === 'list'" class="preferences-list">
        <div v-for="(item, index) in categoryPreferences" :key="item.categoryId" class="preference-item">
          <div class="rank">{{ index + 1 }}</div>
          <div class="category">{{ getCategoryName(item.categoryId) }}</div>
          <el-progress
            :percentage="getPercentage(item.count)"
            :color="getProgressColor(index)"
            :show-text="false"
            style="flex: 1"
          />
          <div class="count" style="margin-left: 12px">{{ item.count }}次</div>
        </div>
      </div>

      <!-- 饼图视图 -->
      <div v-else class="pie-chart-container">
        <v-chart :option="categoryPieOption" autoresize />
      </div>
    </el-card>

    <!-- 行为历史记录 -->
    <el-card class="history-card">
      <template #header>
        <div class="card-header">
          <span>行为历史</span>
          <el-radio-group v-model="chartType" size="small">
            <el-radio-button label="table">表格</el-radio-button>
            <el-radio-button label="pie">饼图</el-radio-button>
          </el-radio-group>
        </div>
      </template>
      
      <!-- 表格视图 -->
      <div v-if="chartType === 'table'">
        <el-table :data="behaviorHistory" v-loading="loading" style="width: 100%">
          <el-table-column prop="createTime" label="时间" width="180">
            <template #default="{ row }">
              {{ formatDate(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="behaviorType" label="行为类型" width="120">
            <template #default="{ row }">
              <el-tag :type="getBehaviorTagType(row.behaviorType)">
                {{ getBehaviorLabel(row.behaviorType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="count" label="次数" width="100">
            <template #default="{ row }">
              {{ row.count }}
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50]"
            :total="total"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>

      <!-- 饼图视图 -->
      <div v-else class="pie-chart-container">
        <v-chart :option="behaviorPieOption" autoresize />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import {
  View,
  Star,
  ShoppingCart,
  Timer,
  DataLine
} from '@element-plus/icons-vue'
import {
  getUserBehaviorHistory,
  getUserCategoryPreferences,
  getUserBehaviorTrend
} from '@/api/statistics'
import { getCategoryTree } from '@/api/category'

// 注册必需的组件
use([
  CanvasRenderer,
  LineChart,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

const route = useRoute()
const userId = computed(() => route.params.id)

// 行为类型定义
const behaviorTypes = [
  { label: '浏览', value: 'BROWSE' },
  { label: '搜索', value: 'SEARCH' },
  { label: '收藏', value: 'FAVORITE' }
]

// 获取行为标签文本
const getBehaviorLabel = (type) => {
  const found = behaviorTypes.find(t => t.value === type)
  return found ? found.label : type
}

// 获取行为标签类型
const getBehaviorTagType = (type) => {
  const types = {
    BROWSE: '',
    SEARCH: 'warning',
    FAVORITE: 'success'
  }
  return types[type] || 'info'
}

// 状态定义
const loading = ref(false)
const currentBehaviorType = ref('BROWSE')
const trendDays = ref(7)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 数据状态
const behaviorHistory = ref([])
const categoryPreferences = ref([])
const behaviorTrendData = ref({
  dates: [],
  counts: []
})

// 行为趋势图表配置
const trendChartOption = computed(() => ({
  title: {
    text: `用户${getBehaviorLabel(currentBehaviorType.value)}趋势`
  },
  tooltip: {
    trigger: 'axis',
    formatter: function(params) {
      const date = params[0].axisValue
      const count = params[0].data
      return `${date}<br/>${getBehaviorLabel(currentBehaviorType.value)}：${count}次`
    }
  },
  xAxis: {
    type: 'category',
    data: behaviorTrendData.value.dates.map(date => 
      `${date[0]}-${String(date[1]).padStart(2, '0')}-${String(date[2]).padStart(2, '0')}`
    ),
    axisLabel: {
      rotate: 45
    }
  },
  yAxis: {
    type: 'value',
    name: '次数',
    minInterval: 1
  },
  series: [
    {
      name: getBehaviorLabel(currentBehaviorType.value),
      type: 'line',
      data: behaviorTrendData.value.counts,
      smooth: true,
      symbol: 'circle',
      symbolSize: 6,
      itemStyle: {
        color: '#409EFF'
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            {
              offset: 0,
              color: 'rgba(64,158,255,0.2)'
            },
            {
              offset: 1,
              color: 'rgba(64,158,255,0)'
            }
          ]
        }
      }
    }
  ]
}))

// 获取行为历史
const fetchBehaviorHistory = async () => {
  if (!userId.value) return

  try {
    loading.value = true
    const res = await getUserBehaviorHistory(userId.value, {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    })
    if (res.code === 200 && res.data) {
      behaviorHistory.value = res.data || []
      total.value = res.data.length || 0
    }
  } catch (error) {
    console.error('获取行为历史失败:', error)
    ElMessage.error('获取行为历史失败')
  } finally {
    loading.value = false
  }
}

// 获取分类偏好
const fetchCategoryPreferences = async () => {
  if (!userId.value) return

  try {
    const res = await getUserCategoryPreferences(userId.value, 5)
    if (res.code === 200 && res.data) {
      categoryPreferences.value = res.data
    }
  } catch (error) {
    console.error('获取分类偏好失败:', error)
    ElMessage.error('获取分类偏好失败')
  }
}

// 获取用户行为趋势
const fetchBehaviorTrend = async () => {
  try {
    const res = await getUserBehaviorTrend(
      route.params.id,
      currentBehaviorType.value,
      trendDays.value
    )
    if (res.code === 200 && res.data) {
      // 将对象格式转换为数组格式
      const trendData = Object.entries(res.data).map(([date, count]) => ({
        date: date.split('-').map(Number), // 将日期字符串转换为数组格式 [year, month, day]
        count
      }))

      // 按日期排序
      trendData.sort((a, b) => {
        const dateA = new Date(a.date[0], a.date[1] - 1, a.date[2])
        const dateB = new Date(b.date[0], b.date[1] - 1, b.date[2])
        return dateA - dateB
      })

      // 更新图表数据
      behaviorTrendData.value = {
        dates: trendData.map(item => item.date),
        counts: trendData.map(item => item.count)
      }
    }
  } catch (error) {
    console.error('获取行为趋势失败:', error)
    ElMessage.error('获取行为趋势失败')
  }
}

// 格式化日期
const formatDate = (dateArray) => {
  if (!dateArray || !Array.isArray(dateArray)) return ''
  const [year, month, day, hour, minute] = dateArray
  return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')} ${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`
}

// 获取进度条颜色
const getProgressColor = (index) => {
  const colors = ['#f56c6c', '#e6a23c', '#409eff', '#67c23a', '#909399']
  return colors[index] || colors[colors.length - 1]
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchBehaviorHistory()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchBehaviorHistory()
}

// 监听用户ID变化
watch(
  () => route.params.id,
  (newId) => {
    if (newId) {
      fetchBehaviorHistory()
      fetchCategoryPreferences()
      fetchBehaviorTrend()
    }
  },
  { immediate: true }
)

onMounted(() => {
  fetchCategoryTree()
  if (userId.value) {
    fetchBehaviorHistory()
    fetchCategoryPreferences()
    fetchBehaviorTrend()
  }
})

// 在 script setup 中添加以下内容
const chartType = ref('table')
const preferenceViewType = ref('list')

// 计算饼图数据
const behaviorPieOption = computed(() => {
  // 按行为类型分组并计算总次数
  const groupedData = behaviorHistory.value.reduce((acc, curr) => {
    if (!acc[curr.behaviorType]) {
      acc[curr.behaviorType] = {
        count: 0,
        type: curr.behaviorType
      }
    }
    acc[curr.behaviorType].count += curr.count
    return acc
  }, {})

  // 转换为饼图所需的数据格式
  const pieData = Object.values(groupedData).map(item => ({
    name: getBehaviorLabel(item.type),
    value: item.count
  }))

  return {
    title: {
      text: '用户行为分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      padding: 5
    },
    series: [
      {
        name: '行为分布',
        type: 'pie',
        radius: '50%',
        data: pieData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: '{b}: {c}次 ({d}%)'
        }
      }
    ]
  }
})

// 替换原有的categoryMap定义
const categoryMap = ref({})

// 添加获取分类树的方法
const fetchCategoryTree = async () => {
  try {
    const res = await getCategoryTree()
    if (res.code === 200 && res.data) {
      // 将分类树扁平化为映射对象
      const flattenCategories = (categories, map = {}) => {
        categories.forEach(category => {
          map[category.id] = category.name
          if (category.children && category.children.length > 0) {
            flattenCategories(category.children, map)
          }
        })
        return map
      }
      categoryMap.value = flattenCategories(res.data)
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
  }
}

// 修改获取分类名称的方法
const getCategoryName = (categoryId) => {
  return categoryMap.value[categoryId] || `分类${categoryId}`
}

// 计算百分比
const getPercentage = (count) => {
  const total = categoryPreferences.value.reduce((sum, item) => sum + item.count, 0)
  return total > 0 ? (count / total * 100).toFixed(1) : 0
}

// 分类偏好饼图配置
const categoryPieOption = computed(() => {
  const pieData = categoryPreferences.value.map(item => ({
    name: getCategoryName(item.categoryId),
    value: item.count
  }))

  return {
    title: {
      text: '分类偏好分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}次 ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      padding: 5
    },
    series: [
      {
        name: '分类偏好',
        type: 'pie',
        radius: '50%',
        data: pieData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: '{b}: {c}次\n{d}%'
        }
      }
    ]
  }
})
</script>

<style scoped>
.user-analysis {
  padding: 20px;
}

.behavior-stats-card,
.trend-card,
.preferences-card,
.history-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 16px;
  font-weight: bold;
}

.stat-card {
  margin-bottom: 20px;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.stat-icon {
  font-size: 48px;
  margin-right: 20px;
}

.stat-icon.view {
  color: #409eff;
}

.stat-icon.favorite {
  color: #e6a23c;
}

.stat-icon.purchase {
  color: #67c23a;
}

.stat-info {
  flex: 1;
}

.stat-label {
  font-size: 14px;
  color: var(--el-text-color-secondary);
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: var(--el-text-color-primary);
}

.chart-container {
  height: 400px;
}

.preferences-list {
  padding: 0 20px;
}

.preference-item {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.rank {
  width: 24px;
  height: 24px;
  line-height: 24px;
  text-align: center;
  background-color: #f2f6fc;
  border-radius: 50%;
  margin-right: 12px;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.category {
  width: 120px;
  margin-right: 20px;
  font-size: 14px;
  color: var(--el-text-color-primary);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.pie-chart-container {
  height: 400px;
  margin: 20px 0;
}
</style> 